<?php
	/**
	 * Class that handles all database related actions.
	 */
	class Database {
		
		var $link;
		
		/** Establishes a connection with the system's database. */
		function __construct() {
			
			$server = "localhost";
			$userName = "root";
			$password = "root";
			$database = "OpenGroups";
			
			$this->link = mysql_connect($server, $userName, $password) or die("Could not connect to server: " . mysql_error());
			mysql_select_db($database) or die("Could not select database.");
		}
		
		/** Destroys the database connection. */
		function disconnect() {
			mysql_close($this->link);
		}
		
		/**
		 * Executes a single query.
		 * @param $query The query to execute.
		 * @return The result of the select query.
		 */
		function execute($query) { 
			
			$result = mysql_query($query, $this->link) or die("Query failed: " . mysql_error());
			return $result;
		}
		
		/**
		 * Executes an list of queries as a single transaction.
		 * @param $queries The list queries to execute.
		 * @return The result of the last select query.
		 */
		function transaction($queries) {
			
			$result = null;
			
			$this->execute("START TRANSACTION");
			for ($i = 0; $i < sizeof($queries); $i++) {
				$result = $this->execute($queries[$i]);
			}
			$this->execute("COMMIT");
			
			return $result;
		}
		
		/**
		 * Generates a new UID.
		 * @return The generated UID. 
		 */
		function generateUID() {
			
			$result = $this->execute("SELECT uuid() AS newUID");
			$row = mysql_fetch_assoc($result);
			return $row["newUID"];
		}
		
		/**
		 * Builds up a query, blocking SQL injection.
		 * @param $query The template query to build.
		 * @return The clean query.
		 */
		static function buildQuery($query) {
			
			$args  = func_get_args();
			$query = array_shift($args);
			
			$query = str_replace("%", "%%", $query);
			$query = str_replace("?", "%s", $query);
			$args  = array_map('mysql_real_escape_string', $args);
			
			foreach($args as $key=>$value) {
				
				if($value == "") {
					$args[$key] = "null";
				} else {
					$args[$key] = '"' . $value . '"';
				}
			}
			
			array_unshift($args, $query);
			$query = call_user_func_array('sprintf', $args);
			
			return $query;
		}
	}
?>